package com.cwb.study.springbootstudy.utill;

/**
 * 文件上传工具类
 * Created by Administrator on 2019/5/6 0006.
 */

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUpload {
    /**
     * 文件上传处理
     *
     * @param realpath 保存本地路径
     * @param file     文件
     * @param module   分类文件夹名
     * @return filename 文件名
     */
    public static String writeUploadFile(String realpath, MultipartFile file, String module) {
        String filename = file.getOriginalFilename();
        Date date = new Date();
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");
//      String realpath = "D:/image/" + module + "/";
        realpath += module + "/";
        File fileDir = new File(realpath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        String extname = FilenameUtils.getExtension(filename);
        String allowImgFormat = "gif,jpg,jpeg,png";
        if (!allowImgFormat.contains(extname.toLowerCase())) {
            return "NOT_IMAGE";
        }

//        filename = Math.abs(file.getOriginalFilename().hashCode()) + RandomUtils.createRandomString(4) + "." + extname;
        filename = format1.format(date) + "." + extname;
        InputStream input = null;
        FileOutputStream fos = null;
        try {
            input = file.getInputStream();
            fos = new FileOutputStream(realpath + "/" + filename);
            IOUtils.copy(input, fos);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(fos);
        }

        return filename;
    }
}
